#include "list.h"
//#include <assert.h>
//#include <stdlib.h>
//#include <stdio.h>
void Printf(listnode*phead)
{
	listnode* pcur = phead;
	while (pcur)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

listnode* ListBuynode(ListDatatype x)
{
	listnode* ps = (listnode*)malloc(sizeof(listnode));
	if (ps == NULL)
	{
		perror("malloc failed !");
		exit(1);
	}
	ps->data = x;
	ps->next = NULL;
	return ps;
}

void SLTPushBack(listnode** pphead, ListDatatype x)
{
	assert(pphead);
	listnode* tmp = ListBuynode(x);
	if (*pphead == NULL)
		*pphead = tmp;
	else
	{
		listnode* pcur = *pphead;
		while (pcur->next)
			pcur = pcur->next;
		pcur->next = tmp;
	}
}

void SLTPushFront(listnode** pphead, ListDatatype x)
{
	assert(pphead);
	listnode* tmp = ListBuynode(x);
	if (*pphead == NULL)
		SLTPushBack(pphead, x);
	else
	{
		tmp->next = *pphead;
		*pphead = tmp;
	}
}

void SLTPopBack(listnode**pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		listnode* prev = *pphead;
		listnode* tmp = NULL;
		while (prev->next)
		{
			tmp = prev;
			prev = prev->next;
		}
		tmp->next = NULL;
		free(prev);
		prev = NULL;
	}
}

void SLTPopFront(listnode** pphead)
{
	assert(pphead && *pphead);
	listnode* pcur = *pphead;
	*pphead=(*pphead)->next;
	free(pcur);
	pcur = NULL;
}

listnode* find(listnode* phead, ListDatatype x)
{
	assert(phead);
	listnode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void SLTInsert(listnode** pphead, listnode* phead, ListDatatype x)
{
	assert(phead && *pphead);
	//listnode* tmp = NULL;
	if (*pphead == phead)
		SLTPushFront(pphead,x);
	else
	{
		listnode* tmp1 = ListBuynode(x);
		listnode* prev = *pphead;
		while (prev->next != phead)
			//tmp = prev;
			prev = prev->next;
		listnode* tmp = prev->next;
		tmp1->next = tmp;
		prev->next = tmp1;
	}
}

void SLTInsertAfter(listnode* pos, ListDatatype x)
{
	assert(pos);
	listnode* tmp = ListBuynode(x);
	listnode* pcur = pos->next;
	tmp->next = pcur;
	pos->next = tmp;
}

void SLTErase(listnode** pphead, listnode* pos)
{
	assert(*pphead && pos);
	if (pos == *pphead)
		SLTPopFront(pphead);
	else
	{
		listnode* prev = *pphead;
		while (prev->next != pos)
			//tmp = prev;
			prev = prev->next;
		listnode* pcur = prev->next;
		prev->next = prev->next->next;
		free(pcur);
		pcur = NULL;
	}
}

void SLTEraseAfter(listnode* pos)
{
	assert(pos&&pos->next!=NULL);
	listnode* tmp = pos->next;
	listnode* pcur = pos->next->next;
	pos->next = pcur;
	free(tmp);
	tmp = NULL;
}

void SListDestroy(listnode** pphead)
{
	assert(*pphead && pphead);
	listnode* pcur = *pphead;
	while (pcur)
	{
		listnode* tmp = pcur->next;
		free(pcur);
		pcur = tmp;
	}
	*pphead = NULL;
}